<template>
  <view>
    <my-layouts :topHeight="topHeight" :bottomHeight="bottomHeight">
      <!-- 固定头部内容 -->
      <view class="top-box" slot="top">
        <!-- 自定义导航栏 -->
        <u-navbar autoBack placeholder :title="orderdetail.name + '接诊'"></u-navbar>
        <view class="doctor-top">
          <view class="report-doctor flexrow">
            <view>
              <image :src="orderdetail.headImage
                ? baseurl + orderdetail.headImage
                : 'https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/avatar.png'
                " mode="aspectFill"></image>
            </view>
            <view class="report-doctorright">
              <view class="flexrow flexbetween">
                <view>
                  {{ orderdetail.name || "医生" }}
                  {{ orderdetail.jobTitle || "" }}
                </view>
                <view class="fontsize12 doctoebtn" @click="todoctordetail">
                  医生详情
                </view>
              </view>
              <view class="fontsize14 magintop4 flexrow flexbetween">
                <view class="color999">
                  {{ orderdetail.hospitalName || "" }}
                  {{ orderdetail.departmentName || "" }}
                </view>
                <view>距离：{{ orderdetail.distance || 0 }}km</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 滚动区域内容 -->
      <view class="scroll-box" slot="scroll" :style="{
        minHeight: `calc(100vh - ${topHeight} - ${bottomHeight})`,
        backgroundColor: '#f7f7f7',
      }">
        <!-- 会话交流组件 -->
        <view class="conversation">
          <!-- 聊天内容列表 -->
          <view class="message-list">
            <template v-if="isCompleted">
              <!-- 没有更多了 -->
              <u-loadmore style="margin-bottom: 40rpx" v-if="isCompleted" status="nomore"></u-loadmore>
              <!-- 描述症状内容 -->
              <view class="message-item reverse">
                <u-avatar src="" size="80rpx" default-url="/static/avatar.png"></u-avatar>
                <view class="item-right">
                  <!-- <view class="name">
										{{ orderdetail.name + " 医生" }}
									</view> -->
                  <view class="time">{{ orderInfo.createDate || "" }}</view>
                  <view class="content">
                    <view class="miaoshu-zhengzhuang">
                      <view class="miaoshu-item">
                        <text style="color: #666">病情描述：</text>
                        {{ orderInfo.depict || "" }}
                      </view>
                      <view class="miaoshu-img" v-if="orderInfo.depictImage">
                        <image @click="handlePreviewImage(baseurl + item)" class="img" :key="index"
                          v-for="(item, index) in orderInfo.depictImage" :src="baseurl + item" mode="aspectFill">
                        </image>
                      </view>
                      <!-- <view class="miaoshu-item">
												<text style="color: #666;">患病时长：</text>
												{{ orderInfo.duration || "" }}
											</view> -->
                      <view class="miaoshu-item">
                        <text style="color: #666">医院检查：</text>
                        {{ orderInfo.examine || "" }}
                      </view>
                      <!-- <view class="miaoshu-item">
												<text style="color: #666;">用药情况：</text>
												{{ orderInfo.medication || "" }}
											</view> -->
                      <view class="miaoshu-img" v-if="orderInfo.imageUrls">
                        <image @click="handlePreviewImage(baseurl + item)" class="img" :key="index"
                          v-for="(item, index) in orderInfo.imageUrls" :src="baseurl + item" mode="aspectFill"></image>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
            <template v-for="(item, index) in messageList">
              <view v-if="!item.isDeleted" :key="item.ID" class="message-item"
                :class="{ reverse: item.from == userId }">
                <!-- 撤回消息 -->
                <view v-if="item.isRevoked" class="revoked-message-box">
                  <view class="revoked-message" v-if="item.from == userId">
                    您撤回了一条消息
                  </view>
                  <view class="revoked-message" v-else>
                    {{ orderdetail.name || "医生" }}撤回了一条消息
                  </view>
                </view>
                <!-- 问诊将在查看病例报告24小时后结束 -->
                <view v-else-if="
                  item.payload &&
                  item.payload.data === 'createDiseaseCaseCountDown'
                " class="revoked-message-box">
                  <view class="revoked-message">
                    您好，该问诊将在您首次查看病例报告24小时后结束
                  </view>
                </view>
                <template v-else>
                  <u-avatar :src="item.from == userId ? '' : baseurl + orderdetail.headImage
                    " size="80rpx"
                    default-url="https://applet.youtuyiliao.com/profile/upload/xiaochengxu/static/avatar.png"></u-avatar>
                  <view class="item-right">
                    <view class="name" v-if="item.from != userId">
                      {{ orderdetail.name || "医生" }}
                    </view>
                    <view class="time">{{ item.time | filterTime }}</view>
                    <!-- 图片内容 -->
                    <view v-if="item.payload && item.payload.data === 'image'" @longpress="longpress(item)" @click="
                      handlePreviewImage(
                        item.payload && item.payload.description
                      )
                      ">
                      <u-image width="300rpx" height="300rpx" radius="16rpx" :fade="false" :src="baseurl +(item.payload && item.payload.description)
                        | filterImgUrl
                        " mode="aspectFill"></u-image>
                    </view>
                    <!-- 视频内容 -->
                    <view v-else-if="item.payload && item.payload.data === 'video'" class="content-video"
                      @click="handleVideoPlay(item.payload.description)">
                      <image class="video-bg" src="/static/message/video-bg.png" mode="aspectFill"></image>
                      <image class="video-play" src="/static/message/video-play.png" mode=""></image>
                      <text class="video-time">
                        {{
                          (item.payload && item.payload.description)
                          | filterVideoTime
                        }}
                      </text>
                    </view>
                    <!-- 带边距的内容 -->
                    <view class="content-box" v-else>
                      <view class="content-wrap">
                        <view class="content" @longpress="handleRevokeMessage(item)">
                          <!-- 文本内容 -->
                          <text class="text" v-if="item.type === 'TIMTextElem'">
                            {{ item.payload && item.payload.text }}
                          </text>
                          <!-- 病历报告已生成 -->
                          <view v-else-if="
                            item.payload &&
                            item.payload.data === 'createDiseaseCase'
                          " class="case-report" @click="goCaseReport">
                            病历报告已生成,点击查看
                          </view>
                          <!-- 上门时间 -->
                          <view class="shangmen-time" v-else-if="
                            item.payload &&
                            item.payload.data === 'sendVisitDate'
                          ">
                            <view class="shangmen-one">
                              {{ item.payload && item.payload.description }}上门
                            </view>
                            <!-- <view class="shangmen-two">已同意</view> -->
                            <view class="flexrow flexaround" style="width: 100%">
                              <my-button borderRadius="8" height="64" width="140" hoverClass="none" border
                                @click="visitcancel(item, index)">
                                拒绝
                              </my-button>
                              <my-button borderRadius="8" height="64" width="140" hoverClass="none" background="#3FA3FA"
                                @click="comfirmvisit(item, index)">
                                同意
                              </my-button>
                            </view>
                          </view>
                          <!-- 拒绝上门时间 -->
                          <view class="shangmen-time" v-else-if="
                            item.payload &&
                            item.payload.data === 'refuseVisitDate'
                          ">
                            <view class="shangmen-one">
                              {{ item.payload && item.payload.description }}上门
                            </view>
                            <view class="shangmen-two">已拒绝</view>
                          </view>
                          <!-- 同意上门时间 -->
                          <view class="shangmen-time" v-else-if="
                            item.payload &&
                            item.payload.data === 'confirmVisitDate'
                          ">
                            <view class="shangmen-one">
                              {{ item.payload && item.payload.description }}上门
                            </view>
                            <view class="shangmen-two">已同意</view>
                          </view>
                          <!-- 辅料清单 -->
                          <view class="shangmen-time" v-else-if="
                            item.payload &&
                            item.payload.data === 'materielProduct'
                          ">
                            <view class="shangmen-one" style="color: #3fa3fa"
                              @click="goMaterialsList(item.payload.extension)">
                              辅料清单，点击查看
                            </view>
                            <view class="shangmen-two">
                              {{
                                (item.payload &&
                                  item.payload.description &&
                                  item.payload.description.slice(0, 1)) === "1"
                                  ? "未付款"
                                  : "已付款"
                              }}
                            </view>
                          </view>
                          <!-- 结束问诊 -->
                          <view class="shangmen-time" v-else-if="
                            item.payload && item.payload.data === 'orderOver'
                          ">
                            <view class="shangmen-one" style="color: #3fa3fa">
                              治疗已完成
                            </view>
                            <view class="shangmen-two">已确认</view>
                          </view>
                          <!-- 语音内容 -->
                          <view class="audio-box" v-else-if="
                            item.payload && item.payload.data === 'audio'
                          " @click="hanlePlayRecord(item)" @longpress="longpress(item)">
                            <image class="audio-img" :src="item.audioPlay
                              ? '/static/message/icon-pause.png'
                              : '/static/message/icon-play.png'
                              " mode=""></image>
                            <image class="audio-bolang" src="/static/message/icon-bolang.png" mode=""></image>
                            <text class="audio-text">
                              {{
                                (item.payload && item.payload.description)
                                | filterAudioTime
                              }}
                            </text>
                          </view>
                        </view>
                        <!-- 转文字按钮 -->
                        <view v-if="
                          item.payload &&
                          item.payload.data === 'audio' &&
                          !item.isAudioToText
                        " class="change-text-btn" @click="handleAudioToText(item)">
                          转文字
                        </view>
                      </view>
                      <!-- 语音转文字内容 -->
                      <view class="content-wrap2" v-if="
                        item.payload &&
                        item.payload.data === 'audio' &&
                        item.isAudioToText
                      ">
                        <view class="change-text-content">
                          {{ item.audioText }}
                        </view>
                      </view>
                    </view>
                  </view>
                </template>
              </view>
            </template>
          </view>
        </view>
      </view>

      <!-- 固定底部内容 -->
      <view class="bottom-box" slot="bottom">
        <view v-if="isTreatComplete" class="overbox-bottom fontsize14">
          本次治疗已完成
        </view>
        <template v-else>
          <!-- 底部输入框 -->
          <view class="bottom-one">
            <!-- 语音图片 -->
            <image class="icon" src="../../static/message/icon-yuyin.png" mode="" @click="handleRecord"></image>
            <view class="textarea-box">
              <textarea class="textarea" auto-height v-model="message" :maxlength="-1" :cursor-spacing="20" />
            </view>
            <my-button v-if="message.length > 0" width="112" height="56" fontSize="24" borderRadius="8"
              @click="_sendMessage">
              发送
            </my-button>
            <!-- 加减号按钮 -->
            <image v-else class="icon" :src="showBottom
              ? 'https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/jian.png'
              : 'https://bedfamily.eos.xian-2.cmecloud.cn/profile/xiaochengxu/static/jia.png'
              " @click="handleChangeBottom" mode=""></image>
          </view>
          <!-- 底部操作内容 -->
          <view class="bottom-two">
            <!-- 图片 -->
            <view class="bottom-item" @click="_sendImageMessage">
              <image class="item-img" src="../../static/message/photo.png" mode=""></image>
              <view class="item-text">图片</view>
            </view>
            <!-- 视频 -->
            <view class="bottom-item" @click="_sendVideoMessage">
              <image class="item-img" src="../../static/message/video.png" mode=""></image>
              <view class="item-text">视频</view>
            </view>
            <!--聊天记录  -->
            <view class="bottom-item" @click="chatrecord">
              <image class="item-img" src="https://applet.youtuyiliao.com/profile/upload/xiaochengxu/static/record.png"
                mode=""></image>
              <view class="item-text">聊天记录</view>
            </view>
          </view>
        </template>
      </view>
    </my-layouts>
    <!-- 撤回消息弹框 -->
    <my-dialog ref="revokeMessageRef" content="您确定要撤回这条消息吗？" @confirm="_revokeMessage"></my-dialog>
    <!-- 录音弹框 -->
    <record ref="recordRef" @confirm="_sendAudioMessage"></record>
    <!-- 视频 -->
    <video v-if="!!videoUrl" id="my-video" :src="videoUrl" controls
      @fullscreenchange="handleVideoFullScreenChange"></video>
  </view>
</template>

<script>
import record from "../../components/record.vue";
import {
  confirmVisitDate,
  getOrderDepict,
  recordingRecognition,
} from "../../api/index.js";
import MyLayouts from "@/chronicDisease/components/my-layouts/my-layouts.vue";
import MyDialog from "@/chronicDisease/components/my-dialog/my-dialog.vue";
import MyButton from "@/chronicDisease/components/my-button/my-button.vue";
export default {
  components: {
    record,
    MyLayouts,
    MyDialog,
    MyButton
  },
  data() {
    return {
      orderNumber: "", // 订单号
      userId: "", // userId
      nextReqMessageID: "", // 下一条消息的id
      patientRecordsInfo: {}, // 患者记录信息
      message: "", // 文字消息内容
      textAreaHeight: uni.upx2px(76), // 文本域高度
      showBottom: false, // 是否显示底部内容
      ifCase: 1,
      ifMateriel: 1,
      messageList: [], // 聊天消息列表
      orderdetail: {}, //订单信息
      baseurl: "", //地址前缀
      revokeMessageInfo: {},
      timer: "", //定时器
      isCompleted: false,
      requestCount: 0, //默认请求次数
      scrollHeight: 0, //滚动高度
      orderInfo: {}, //订单描述信息
      innerAudioContext: null,
      videoUrl: "", //视频url
      videoContext: null, // 视频上下文
    };
  },
  filters: {
    // filterImgUrl: (url) => {
    //   if (!url) return "";
    //   // 如果是完整地址了，就显示完整地址，否则拼接baseUrl
    //   if (/^http(s)?:\/\//.test(url)) return url;
    //   return this.$store.state.chronic.baseUrl + url;
    // },
    filterTime(time) {
      return uni.$dayjs(time * 1000).format("YYYY-MM-DD HH:mm:ss");
    },
    filterAudioTime(description) {
      const time = Number(description.split("|")[1]) || 0;
      if (time < 60) {
        return `${time % 60}"`;
      } else {
        return `${Math.floor(time / 60)}'${time % 60}"`;
      }
    },
    // 过滤视频时间
    filterVideoTime(description) {
      if (!description) return "0:00";
      const videoTime = Number(description.split("|")[1]) || 0;
      // 超过60秒的 按照几分几秒显示
      if (videoTime >= 60)
        return `${Math.floor(videoTime / 60)}:${(videoTime % 60)
          .toString()
          .padStart(2, "0")}`;
      return `0:${videoTime.toString().padStart(2, "0")}`;
    },
  },
  computed: {
    topHeight() {
      const { statusBarHeight } = uni.getSystemInfoSync() || {};
      return uni.upx2px(148) + 44 + (statusBarHeight || 0) + "px";
    },
    bottomHeight({ textAreaHeight, showBottom }) {
      if (this.isTreatComplete) return textAreaHeight + uni.upx2px(32) + "px";
      return showBottom
        ? textAreaHeight + uni.upx2px(32) + uni.upx2px(312) + "px"
        : textAreaHeight + uni.upx2px(32) + "px";
    },
    // 是否治疗完成
    isTreatComplete({ orderdetail, messageList }) {
      const flag = messageList.some((item) => {
        return item.payload && item.payload.data === "orderOver";
      });
      if (flag) {
        return true;
      }
      if (!orderdetail.overDate) return false;
      const currentTimestamp = +new Date();
      // 判断查看病例后24小时后结束问诊
      const createDiseaseCaseCountDownTimestamp = messageList.find(
        (item) => item.payload?.data === "createDiseaseCaseCountDown"
      )?.payload?.description;
      if (createDiseaseCaseCountDownTimestamp) {
        return (
          currentTimestamp >=
          +createDiseaseCaseCountDownTimestamp + 24 * 60 * 60 * 1000
        );
      }
      // 如果当前时间戳，大于等于治疗结束时间戳，就代表治疗结束了
      const overDateTimestamp = this.$dayjs(orderdetail.overDate).valueOf();
      return currentTimestamp >= overDateTimestamp;
    },
  },
  watch: {
    // 监听文本框变化，动态修改文本框高度
    message(val) {
      if (!val) {
        this.textAreaHeight = uni.upx2px(76);
      } else {
        this.$nextTick(async () => {
          const result = await this.$utils.getRect(".textarea-box");
          this.textAreaHeight = result.height;
        });
      }
    },
  },
  onLoad(options) {
       this.baseurl = this.$store.state.chronic.imageUrl
	console.log('baseurl', this.baseurl);
    let orderdetail = JSON.parse(decodeURIComponent(options.orderdetail));
    this.userId = uni.getStorageSync("userId");

    if (options.orderdetail) {
      console.log("订单信息", orderdetail);
      this.orderdetail = orderdetail;
      this._getMessageList();
      this._getOrderDepict();
      if (this.$im.sdkReady) {
        // 监听收到新消息
        this.$im.tim.on(
          this.$im.TIM.EVENT.MESSAGE_RECEIVED,
          this._onMessageReceived
        );
      }
    }
  },
  onPageScroll(e) {
    // 加载完毕聊天记录就不用执行后面的了
    if (this.isCompleted) return;
    this.$u.debounce(() => {
      const scrollTop = e.scrollTop;
      if (scrollTop <= 50) {
        console.log("滚到顶部了");
        this._getMessageList();
      }
    }, 200);
  },
  onUnload() {
    // 取消监听收到新消息
    this.$im.tim.off(
      this.$im.TIM.EVENT.MESSAGE_RECEIVED,
      this._onMessageReceived
    );
  },
  onShow() {
    if (
      this.$store.getters["pageInfo"]?.createDiseaseCaseCountDown &&
      this.messageList.length > 0
    ) {
      // 判断是否发送过，查看病例后24小时后结束问诊，代表首次查看
      const isSend = this.messageList.some(
        (item) => item.payload?.data === "createDiseaseCaseCountDown"
      );
      if (isSend) return;
      this._sendCustomMessage(
        "createDiseaseCaseCountDown",
        new Date().getTime().toString()
      );
      this.$nextTick(() => {
        this.$store.commit("setPageInfo", {});
      });
    }
  },
  methods: {
    // 播放视频
    handleVideoPlay(description) {
      this.videoUrl = this.baseurl + description.split("|")[0];
      this.$nextTick(() => {
        this.videoContext = uni.createVideoContext("my-video");
        this.videoContext.requestFullScreen({
          direction: 0,
        });
        this.videoContext.play();
      });
    },
    // 视频进入退出全屏的事件
    handleVideoFullScreenChange(e) {
      console.log("视频进入或者退出全屏", e.detail);
      const { fullScreen } = e.detail;
      if (!fullScreen) {
        this.videoContext.pause();
        this.videoUrl = "";
        this.videoContext = null;
      }
    },
    // 发送语音消息
    async _sendAudioMessage(description) {
      await this._sendCustomMessage("audio", description);
    },
    // 打开录音弹框
    handleRecord() {
      this.$refs.recordRef.show = true;
    },
    // 播放语音
    hanlePlayRecord(item) {
      // 正在播放中，点击就停止播放
      if (item.audioPlay) {
        this.innerAudioContext && this.innerAudioContext.stop();
        // 设置语音未播放状态
        this.$set(item, "audioPlay", false);
        return;
      }
      // 将所有语音重置为未播放状态
      this.messageList.forEach((data) => {
        this.$set(data, "audioPlay", false);
      });
      const description = item.payload && item.payload.description;
      const audioUrl = this.baseurl + description.split("|")[0];
      // 语音实例也对应销毁
      this.innerAudioContext && this.innerAudioContext.destroy();
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.src = audioUrl;
      this.innerAudioContext.play();
      this.innerAudioContext.onPlay(() => {
        // 设置语音为播放状态
        this.$set(item, "audioPlay", true);
        console.log("语音开始播放");
      });
      this.innerAudioContext.onEnded(() => {
        // 设置语音为未播放状态
        this.$set(item, "audioPlay", false);
        console.log("语音播放完毕");
      });
      this.innerAudioContext.onError((res) => {
        this.$toast("语音播放失败");
        console.log("语音播放出错", res.errMsg);
        console.log("语音播放出错code", res.errCode);
      });
    },
    // 获取订单描述内容
    _getOrderDepict() {
      getOrderDepict({
        orderNumber: this.orderdetail.orderNumber,
      }).then((res) => {
        if (res.code == 200) {
          console.log("获取订单描述内容", res.data);
          const data = res.data || {};
          if (data.imageUrls) {
            data.imageUrls = data.imageUrls.split(",");
          }
          this.orderInfo = data;
        }
      });
    },
    //查看聊天记录
    chatrecord() {
      uni.navigateTo({
        url:
          "chat-record?orderdetail=" +
          encodeURIComponent(JSON.stringify(this.orderdetail)),
      });
    },
    // 撤回消息api
    async _revokeMessage() {
      await this.$im.revokeMessage(this.revokeMessageInfo);
    },
    // 长按撤回消息弹框
    handleRevokeMessage(item) {
      // 只能撤回自己的消息
      if (item.from !== this.userId) return;
      // 只有文本消息、图片消息、语音消息允许撤回
      if (
        !(
          item.payload.data === "audio" ||
          ["TIMTextElem", "TIMImageElem"].includes(item.type)
        )
      )
        return;
      // 消息时间戳
      const messageTimestamp = item.time * 1000;
      // 当前时间戳
      const currentTimestamp = +new Date();
      // 当前时间戳-消息时间戳 大于等于2分钟不允许撤回
      if (currentTimestamp - messageTimestamp >= 120 * 1000) return;
      this.revokeMessageInfo = item;
      this.$refs.revokeMessageRef.show = true;
    },
    //辅料清单
    goMaterialsList() {
      uni.navigateTo({
        url:
          "accessories/accessories?orderNumber=" + this.orderdetail.orderNumber,
      });
    },
    //取消上门时间
    visitcancel(item, index) {
      this._sendCustomMessage("refuseVisitDate", item.payload.description);
      this.$im.deleteMessage([item]).then((res) => {
        // this.messageList.splice(index,1)
      });
    },
    //同意上门时间
    comfirmvisit(item, index) {
      confirmVisitDate({
        orderNumber: this.orderdetail.orderNumber,
        visitDate: item.payload.description,
      }).then((res) => {
        this._sendCustomMessage(
          "confirmVisitDate",
          item.payload.description
        ).then((res) => {
          this.$im.deleteMessage([item]);
        });
      });
    },
    //查看病例报告
    goCaseReport() {
      uni.navigateTo({
        url:
          "medical-report/medical-report?orderNumber=" +
          this.orderdetail.orderNumber,
      });
    },
    // 监听收到新消息
    _onMessageReceived(e) {
      console.log("收到新消息了", e);
      const data = e.data[0];
      // 只接收当前订单号的消息
      if (
        data.cloudCustomData === this.orderdetail.orderNumber ||
        (data.payload && data.payload.extension) ===
        this.orderdetail.orderNumber
      ) {
        this.messageList.push(data);
        // 滚到底部
        this.handleScrollToBottom(100);
      }
    },
    // 预览图片
    handlePreviewImage(url) {
		console.log('url', url);
    this.$utils.previewImage(this.baseurl + url);
    },
    //查看医生详情
    todoctordetail() {
      let doctorId = this.orderdetail.doctorId;
      uni.navigateTo({
        url: "../my/doctor-deatil?doctorId=" + doctorId,
      });
    },
    // 发送文本消息
    async _sendMessage() {
      const res = await this.$im.sendMessage(
        this.orderdetail.doctorId,
        this.message,
        this.orderdetail.orderNumber
      );
      console.log("发送成功", res);

      this.message = "";
      this.messageList.push(res.message);
      // 滚到底部
      this.handleScrollToBottom();
    },
    // 发送图片消息
    async _sendImageMessage() {
      const res = await this.$im.sendImageMessage(
        this.orderdetail.doctorId,
        this.orderdetail.orderNumber
      );
      console.log('发送成功', res);

      this.messageList.push(res.message);
      // 滚到底部
      this.handleScrollToBottom(100);
    },
    // 发送视频消息
    async _sendVideoMessage() {
      const res = await this.$im.sendVideoMessage(
        this.orderdetail.doctorId,
        this.orderdetail.orderNumber
      );
      this.messageList.push(res.message);
      // 滚到底部
      this.handleScrollToBottom(100);
    },

    // 发送自定义消息
    async _sendCustomMessage(data, description) {
      const res = await this.$im.sendCustomMessage(
        this.orderdetail.doctorId,
        data,
        description,
        this.orderdetail.orderNumber
      );
      this.messageList.push(res.message);
      // 滚到底部
      this.handleScrollToBottom(100);
    },
    // 获取聊天记录
    async _getMessageList(count = 15) {
      console.log("this.orderdetail.doctorId", this.orderdetail.doctorId);

      console.log("this.orderdetail.doctorId", this.orderdetail.doctorId);
      console.log("this.nextReqMessageID", this.nextReqMessageID);

      const res = await this.$im.getMessageList(
        "C2C" + this.orderdetail.doctorId,
        this.nextReqMessageID,
        count
      );
      let { messageList, nextReqMessageID, isCompleted } = res || {};
      messageList = (messageList || []).filter(
        (item) =>
          item.cloudCustomData === this.orderdetail.orderNumber ||
          (item.payload && item.payload.extension) ===
          this.orderdetail.orderNumber
      );
      messageList.forEach((item) => {
        item.audioPlay = false;
        item.isAudioToText = false;
        item.audioText = "";
      });
      this.isCompleted = !!isCompleted;
      this.nextReqMessageID = nextReqMessageID || "";
      console.log("isCompleted", isCompleted);
      // 只有第一次进来聊天页面触发初始化滚到底部
      if (this.requestCount === 0) {
        this.messageList.unshift(...messageList);
        if (!isCompleted && this.messageList.length < count) {
          this._getMessageList();
        } else {
          this.requestCount += 1;
          // 延迟200ms，等待渲染完毕
          this.timer && clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.$nextTick(async () => {
              // 初始化记录滚动区域高度
              const container = await this.$utils.getRect(".scroll-box");
              console.log("获取到的节点信息", container);
              this.scrollHeight = container.height;
              this.handleScrollToBottom(0);
            });
          }, 200);
        }
        return;
      }
      this.messageList.unshift(...messageList);
      this.$nextTick(() => {
        // 延迟100ms，有时候居然连文字都渲染不完毕
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(async () => {
          // 定位聊天记录滚动条位置
          const container = await this.$utils.getRect(".scroll-box");
          console.log("获取到的节点信息", container);
          uni.pageScrollTo({
            scrollTop: container.height - this.scrollHeight,
            duration: 0,
            success: () => {
              this.scrollHeight = container.height;
            },
          });
        }, 100);
      });
    },
    // 聊天内容滚动到底部
    handleScrollToBottom(time = 0) {
      if (time > 0) {
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.$nextTick(() => {
            uni.pageScrollTo({
              duration: 0,
              scrollTop: 99999999,
            });
          });
        }, time);
      } else {
        this.$nextTick(() => {
          uni.pageScrollTo({
            duration: 0,
            scrollTop: 99999999,
          });
        });
      }
    },
    // 切换底部显示隐藏
    handleChangeBottom() {
      this.showBottom = !this.showBottom;
    },
    // 开病历报告
    goWriteCaseReport() {
      if (this.ifCase === 2) {
        return this.$utils.showToast("您已创建过病历报告，不可重复创建");
      }
      uni.navigateTo({
        url:
          "/pages/message/write-case-report/write-case-report?patientRecordsInfo=" +
          this.$utils.sendMsg({
            ...this.patientRecordsInfo,
            orderNumber: this.orderNumber,
          }),
      });
    },
    // 语音转文字
    handleAudioToText(item) {
      uni.showLoading({
        title: "努力转换中...",
        mask: true,
        duration: 60000,
      });
      recordingRecognition({
        fileUrl: item.payload && item.payload.description.split("|")[0],
      }).then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          console.log("语音转文字", res.data);
          this.$set(item, "isAudioToText", true);
          this.$set(item, "audioText", res.data || "");
        }
      });
    },
  },
};
</script>
<style>
view,
text {
  box-sizing: border-box;
}
</style>
<style lang="scss" scoped>
.shangmen-address {
  width: 100%;
  height: 88rpx;
  background-color: #fff;
  padding: 0 40rpx;

  text {
    display: inline-block;
    width: 100%;
    font-size: 28rpx;
  }
}

// 固定底部内容
.bottom-box {
  background-color: #fff;

  .overbox-bottom {
    width: 100%;
    color: #3fa3fa;
    text-align: center;
    height: 108rpx;
    line-height: 108rpx;
  }

  .bottom-one {
    width: 100%;
    padding: 16rpx 28rpx;
    display: flex;
    align-items: center;

    .icon {
      width: 56rpx;
      height: 56rpx;
    }

    .textarea-box {
      display: flex;
      align-items: center;
      margin: 0 28rpx;
      width: 0;
      flex: 1;
      max-height: 200rpx;
      overflow-y: auto;
      min-height: 76rpx;
      background-color: #f7f7f7;
      padding: 20rpx 28rpx;

      .textarea {
        width: 100%;
        font-size: 28rpx;
      }
    }
  }

  .bottom-two {
    width: 100%;
    height: 312rpx;
    border-top: 4rpx solid #f7f7f7;
    padding: 32rpx 56rpx;
    background-color: #fff;
    display: flex;

    .bottom-item {
      margin-right: 84rpx;
      text-align: center;

      &:nth-child(4n) {
        margin-right: 0;
      }

      .item-img {
        width: 96rpx;
        height: 96rpx;
      }

      .item-text {
        font-size: 24rpx;
        margin-top: 8rpx;
      }
    }
  }
}

.conversation {
  width: 100%;
}

.message-list {
  width: 100%;
  padding: 40rpx;
}

.message-item {
  width: 100%;
  display: flex;
  flex-direction: row;
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .revoked-message-box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .revoked-message {
      padding: 0 16rpx;
      height: 52rpx;
      background-color: #fff;
      font-size: 20rpx;
      color: #666;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .item-right {
    margin-left: 28rpx;
    width: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .name {
    font-size: 28rpx;
    margin-bottom: 8rpx;
  }

  .time {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 20rpx;
  }

  .content-box {
    width: auto;

    .content-wrap {
      display: flex;
      align-items: center;
    }

    .content-wrap2 {
      display: flex;
      align-items: center;
    }
  }

  // 带边距的内容
  .content {
    width: max-content;
    max-width: 448rpx;
    padding: 24rpx;
    background-color: #fff;
    border-radius: 16rpx;
    font-size: 0;

    // 文本内容
    .text {
      display: inline-block;
      font-size: 32rpx;
      text-align: justify;
      word-break: break-all;
    }

    // 描述症状内容
    .miaoshu-zhengzhuang {
      width: 100%;

      .miaoshu-item {
        font-size: 28rpx;
        margin-bottom: 8rpx;
      }

      .miaoshu-img {
        width: 100%;
        margin-top: 20rpx;
        display: flex;
        flex-wrap: wrap;
        font-size: 0;

        .img {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;

          &:nth-child(3n) {
            margin-right: 0;
          }
        }
      }
    }

    // 病历报告已生成
    .case-report {
      font-size: 28rpx;
      color: #3fa3fa;
    }

    // 上门时间
    .shangmen-time {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .shangmen-one {
        min-width: 340rpx;
        height: 64rpx;
        background-color: rgba(#e0f0fe, 0.3);
        border-radius: 8rpx;
        margin-bottom: 20rpx;
        font-size: 28rpx;
        color: #333;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .shangmen-two {
        min-width: 206rpx;
        padding: 0 68rpx;
        height: 64rpx;
        background-color: rgba(#e0f0fe, 0.3);
        border-radius: 8rpx;
        margin-bottom: 20rpx;
        font-size: 28rpx;
        color: #333;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    // 语音播放
    .audio-box {
      display: flex;
      align-items: center;

      .audio-img {
        width: 32rpx;
        height: 32rpx;
      }

      .audio-bolang {
        width: 76rpx;
        height: 34rpx;
        margin: 0 8rpx;
      }

      .audio-text {
        font-size: 24rpx;
      }
    }
  }

  // 语音转文字内容
  .change-text-content {
    width: max-content;
    max-width: 448rpx;
    padding: 24rpx;
    background-color: #fff;
    border-radius: 16rpx;
    color: #333;
    font-size: 28rpx;
    text-align: justify;
    margin-top: 12rpx;
  }

  // 视频内容
  .content-video {
    width: 172rpx;
    height: 284rpx;
    border-radius: 16rpx;
    overflow: hidden;
    position: relative;

    .video-bg {
      width: 100%;
      height: 100%;
    }

    .video-play {
      width: 60rpx;
      height: 60rpx;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      z-index: 5;
    }

    .video-time {
      font-size: 20rpx;
      color: #fff;
      position: absolute;
      right: 8rpx;
      bottom: 8rpx;
      z-index: 10;
    }
  }

  // 转文字按钮
  .change-text-btn {
    width: 92rpx;
    height: 40rpx;
    background: #ffffff;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20rpx;
    color: #666;
    margin-left: 20rpx;
  }

  // 反转的样式
  &.reverse {
    flex-direction: row-reverse;

    .item-right {
      margin-left: 0;
      margin-right: 28rpx;
      align-items: flex-end;
    }

    .content {
      background-color: #e0f0fe;

      .shangmen-one,
      .shangmen-two {
        background-color: #fff;
      }
    }

    .content-wrap {
      flex-direction: row-reverse;
    }

    .content-wrap2 {
      flex-direction: row-reverse;
    }

    .change-text-btn {
      margin-left: 0;
      margin-right: 20rpx;
    }
  }
}

.report-doctor {
  padding: 22rpx 40rpx;

  image {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .magintop4 {
    margin-top: 8rpx;
  }

  .report-doctorright {
    width: calc(100% - 90rpx);

    .doctoebtn {
      color: #fff;
      background-color: #3fa3fa;
      width: 148rpx;
      height: 56rpx;
      text-align: center;
      line-height: 56rpx;
      border-radius: 8rpx;
    }
  }
}

.doctor-top {
  background-color: #fff;
  width: 100%;
  height: 148rpx;
}
</style>
